/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) Roman Divotkey, 2010-2011

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.cogaen.core.Core;
import org.cogaen.core.UpdateableService;
import org.cogaen.event.EventManager;
import org.cogaen.logging.LoggingService;

public class EntityManager implements UpdateableService {
	
	public static final String NAME = "cogaen.entitymanager";

	private static final String LOGGING_SOURCE = "EntityManager";
	
	private Map<String, Entity> entities = new HashMap<String, Entity>();
	private List<Entity> newEntities = new ArrayList<Entity>();
	private List<Entity> oldEntities = new ArrayList<Entity>();
	private List<Entity> engagedEntities = new ArrayList<Entity>();
	private LoggingService logger;
			
	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public void initialize(Core core) {
		EventManager.getInstance(core);
		this.logger = LoggingService.getInstance(core);
	}
	
	public int getNumEntities() {
		return this.engagedEntities.size();
	}
	
	@Override
	public void update() {		
		// engage new entities
		for (Entity entity : this.newEntities) {
			engageEntity(entity);
		}
		this.newEntities.clear();
		
		// disengage and remove old entities
		for (Entity entity : this.oldEntities) {
			disengageEntity(entity);
			this.entities.remove(entity.getName());			
		}		
		this.oldEntities.clear();	
		
		// update entities
		for (Entity entity : this.engagedEntities) {
			entity.update();
		}
	}
	
	private void engageEntity(Entity entity) {
		entity.engage();
		this.engagedEntities.add(entity);
		this.logger.logDebug(LOGGING_SOURCE, "entity '" + entity.getName() + "' engaged");		
	}
	
	private void disengageEntity(Entity entity) {
		this.engagedEntities.remove(entity);
		entity.disengage();
		this.logger.logDebug(LOGGING_SOURCE, "entity '" + entity.getName() + "' disengaged");
	}
			
	public static EntityManager getInstance(Core core) {
		return (EntityManager) core.getService(NAME);
	}
	
	public void addEntity(Entity entity) {
		Entity oldEntity = this.entities.put(entity.getName(), entity);
		if (oldEntity != null) {
			this.entities.put(oldEntity.getName(), oldEntity);
			throw new RuntimeException("entity with name '" + entity.getName() + "' already exists");
		}
		
		this.newEntities.add(entity);
		this.logger.logDebug(LOGGING_SOURCE, "entity '" + entity.getName() + "' added");
	}
	
	public void removeEntity(Entity entity) {
		// we use removeEntity(String name) in order to ensure that an
		// exception is thrown if specified entity does not exist
		removeEntity( entity.getName() );
	}
	
	public void removeEntity(String name) {
		Entity entity = getEntity(name);
		if (!this.oldEntities.contains(entity)) {
			this.oldEntities.add( getEntity(name) );
		}
		this.logger.logDebug(LOGGING_SOURCE, "entity '" + entity.getName() + "' removed");
	}
		
	public boolean hasEntity(String name) {
		return this.entities.containsKey(name);
	}
	
	public Entity getEntity(String name) {
		Entity entity = this.entities.get(name);
		
		if (entity == null) {
			throw new RuntimeException("entity with name '" + name + "' not found");
		}
		
		return entity;
	}
		
	public void removeAllEntities() {
		for (Entity entity : this.entities.values()) {
			removeEntity(entity);
		}		
	}

	public int numOfEntities() {
		return this.entities.size();
	}
	
	public Iterator<Entity> engagedEntitiesIterator() {
		return this.engagedEntities.iterator();
	}

	public Entity getEntity(int i) {
		return this.engagedEntities.get(i);
	}
	
}
